package util;

import java.awt.Color;
import java.awt.Component;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

public class MarketTableCellRenderer implements TableCellRenderer {

  public MarketTableCellRenderer() {
  }

  @Override
  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {

    DefaultTableCellRenderer defaultRenderer = new DefaultTableCellRenderer();
    JLabel label = (JLabel) defaultRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    TableModel model = table.getModel();
    if(column > 0){
      double buyOrder = 0.0;
      double sellOrder = 0.0;
      int difference = 0;
     
      if (column == 1) {
        sellOrder = Constants._dotNumberToDouble(value.toString());
        buyOrder =_getBestOrder(model,2);
      }
      else if (column == 2) {
        sellOrder =_getBestOrder(model,1);
        buyOrder = Constants._dotNumberToDouble(value.toString());
      }
      
      difference = _calculateDifference(buyOrder, sellOrder);

      if (difference > 0) {
        if (isSelected) {
          label.setBackground(new Color(220, 231, 115));
        }
        else {
          label.setBackground(Constants._getPercentageGradient(difference));
        }
      }
    }

    return label;
  }
  
  private double _getBestOrder(TableModel model, int column){
    double highestOrder = 0.0;
    double lowestOrder = 0.0;
    if(column == 1){
      for (int i = 0; i < model.getRowCount(); i++) {
        lowestOrder = Constants._dotNumberToDouble(model.getValueAt(i, column).toString());
        if (lowestOrder > 0) break;
      }
    }
    
    for (int i = 0; i < model.getRowCount(); i++) {
      double currentOrder = Constants._dotNumberToDouble(model.getValueAt(i, column).toString());
      if (highestOrder < currentOrder & column == 2) highestOrder = currentOrder;
      if (lowestOrder > currentOrder & column == 1 & currentOrder > 0) lowestOrder = currentOrder;
    }
    double order = 0.0;
    if (column == 1) order = lowestOrder;
    if (column == 2) order = highestOrder;
    return order;
  }

  private int _calculateDifference(double buyOrder, double sellOrder) {
    int difference = 0;
    if (sellOrder < buyOrder & sellOrder > 0 & buyOrder > 0) {
      Double percent = (buyOrder / sellOrder) * 100.0;
      difference = percent.intValue() - 100;
    }
    return difference;
  }
}
